<template>
  <div>
    <a-modal
      :title="`级别${model && model.id > 0 ? '编辑' : '新增'}`"
      :width="700"
      :visible="visible"
      :confirmLoading="loading"
      @ok="
        () => {
          $emit('ok')
        }
      "
      @cancel="
        () => {
          $emit('cancel')
        }
      "
    >
      <a-spin :spinning="loading">
        <a-form :form="form" :labelCol="{ sm: { span: 4 } }" :wrapperCol="{ sm: { span: 20 } }">
          <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
          <a-form-item v-show="model && model.id > 0" label="ID">
            <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
          </a-form-item>
          <a-form-item label="级别名称">
            <a-input
              v-decorator="['name', { rules: [{ required: true, message: '级别名称不能为空' }] }]"
              placeholder="请输入级别名称"
            />
          </a-form-item>
          <a-form-item label="级别类型">
            <a-select
              v-decorator="['type', { rules: [{ required: true, message: '请选择级别类型' }] }]"
              placeholder="请选择级别类型"
            >
              <a-select-option v-for="it in typeArr" :key="it.id" :value="Number(it.id)">{{ it.text }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="专业类型" v-if="form.getFieldValue('type') == 3">
            <a-select
              v-decorator="['proTypeId', { rules: [{ required: true, message: '请选择专业类型' }] }]"
              placeholder="请选择专业类型"
            >
              <a-select-option v-for="it in projectType" :key="it.id" :value="Number(it.id)">{{
                it.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="最低月薪" v-if="form.getFieldValue('type') == 3">
            <a-input-number :min="0" v-decorator="['minPay']" placeholder="请选择最低月薪"  style="width:150px"/>
          </a-form-item>
          <!-- <a-form-item label="项目类型" v-if="form.getFieldValue('type') == 3 && form.getFieldValue('proTypeId') == 17">
          <a-select v-decorator="['proTypeId', {rules: [{ required: true, message: '请选择项目类型' }]}]"  placeholder="请选择项目类型">
              <a-select-option v-for="it in projectType" :key="it.id" :value="Number(it.id)">{{it.name}}</a-select-option>
            </a-select>
        </a-form-item> -->
          <a-form-item label="级别数值">
            <a-input-number
              :min="0"
              :max="100"
              v-decorator="['levelNum', { rules: [{ required: true, message: '级别等级不能为空' }] }]"
              style="width:150px"
              placeholder="请选择级别数值"
            />
          </a-form-item>
          <a-form-item label="任务所占积分" v-if="form.getFieldValue('type') == 6">
            <a-input-number
              :min="0"
              v-decorator="['integral', { rules: [{ required: true, message: '任务所占积分不能为空' }] }]"
            />
          </a-form-item>

          <a-form-item label="评分要求" v-if="form.getFieldValue('type') == 3 && form.getFieldValue('proTypeId') == 17">
            <a-table
              v-if="level.list.length"
              :columns="columns"
              :data-source="level.list"
              bordered
              size="small"
              :pagination="false"
              :rowKey="(list, index) => index"
            >
              <template v-for="col in ['score_1', 'score_2', 'score_3', 'score_4']" :slot="col" slot-scope="text">
                <div :key="col">{{ text }} %</div>
              </template>
              <template slot="projectId" slot-scope="text">
                <div>{{ text | projectFilter(levelTaskList) }}</div>
              </template>
              <template slot="action" slot-scope="text, scope, index">
                <a @click="handleEdit(index)">编辑</a>
                <a-divider type="vertical" />
                <a @click="handleDel(index)">删除</a>
              </template>
            </a-table>
            <a-button type="dashed" block @click="handleAdd"> <a-icon type="plus" /> 增加 </a-button>
            <!-- levelList -->
          </a-form-item>
          <a-form-item label="积分要求" v-if="form.getFieldValue('type') == 3 && form.getFieldValue('proTypeId') == 17">
            <ul style="display:flex;flex-wrap: wrap;">
              <li v-for="(it, index) in c_integral" :key="index" style="margin-right:20px">
                <span>{{ it.name }}:{{ it.num }}</span>
              </li>
              <a-button type="dashed" @click="handleAddIntegrel"> <a-icon type="edit" /> 编辑 </a-button>
            </ul>
            
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-decorator="['remark']" :rows="4" placeholder="请输入级别备注" />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
    <project-level
      ref="projectLevel"
      :visible="level.visible"
      :loading="level.confirmLoading"
      :model="level.mdl"
      :levelList="levelTaskList"
      @cancel="handleCancel"
      @ok="handleOk"
    ></project-level>
    <integral-form
      ref="integralForm"
      :visible="integral.visible"
      :loading="integral.confirmLoading"
      :model="integral.mdl"
      :levelList="levelList"
      @cancel="handleCancelIntegrel"
      @ok="handleOkIntegrel"
    ></integral-form>
  </div>
</template>
<script>
import pick from 'lodash.pick'
import { projectTypeListByNoAuth, levelListByNoAuth } from '@/api/noAuth'
import { levelTypeList } from '@/utils/other'
import ProjectLevel from './projectLevel'
import IntegralForm from './IntegralForm'
import ShowProjectLevel from './showProjectLevel'
import cloneDeep from 'lodash.clonedeep'
import { levelList } from '@/api/system'

// 表单字段
const fields = ['remark', 'name', 'cType', 'levelNum', 'id', 'type']
const columns = [
  {
    title: '任务',
    dataIndex: 'projectId',
    scopedSlots: { customRender: 'projectId' },
  },
  {
    title: '一星比例',
    dataIndex: 'score_1',
    scopedSlots: { customRender: 'score_1' },
  },
  {
    title: '二星比例',
    dataIndex: 'score_2',
    scopedSlots: { customRender: 'score_2' },
  },
  {
    title: '三星比例',
    dataIndex: 'score_3',
    scopedSlots: { customRender: 'score_3' },
  },
  {
    title: '四星比例',
    dataIndex: 'score_4',
    scopedSlots: { customRender: 'score_4' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  components: {
    ProjectLevel,
    ShowProjectLevel,
    IntegralForm,
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    typeArr: {
      type: Array,
      default: () => [],
    },
    model: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    this.columns = columns
    return {
      form: this.$form.createForm(this),
      projectType: [],
      data: [],
      levelList: [],
      levelTaskList: [],
      // create model
      level: {
        visible: false,
        confirmLoading: false,
        mdl: null,
        type: null,
        list: [],
        handleIndex: null,
      },
      integral: {
        visible: false,
        confirmLoading: false,
        mdl: null,
        type: null,
        data: {},
        handleIndex: null,
      },
      that: this,
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', (n) => {
      if (n) {
        console.log(n)
        let model = pick(this.model, fields)
        console.log(model)
        this.form.setFieldsValue(model)
        if (n.type == 3) {
          console.log(n.type)
          setTimeout(() => this.form.setFieldsValue({ proTypeId: n.proTypeId, minPay: n.minPay || 0 }), 100)
        }
        if (n.mneedJson) {
          this.level.list = []
          let mneedJson = JSON.parse(n.mneedJson)
          let _json = mneedJson.score
          for (let i in _json) {
            console.log(i)
            let it = _json[i]
            for (let index in it) {
              if (index.indexOf('score') != -1) {
                it[index] = it[index] * 100
              }
            }
            this.level.list.push({
              projectId: i,
              ...it,
            })
          }
          console.log(mneedJson,'mneedJson')
          this.integral.data = mneedJson.integral
        }
        setTimeout(() => {
          if (model.type == 6) {
            this.form.setFieldsValue({ integral: this.model.integral })
          }
        }, 100)
      }
    })

    this.getLevelList()
    this.getProjectTypeList()
  },
  methods: {
    getProjectTypeList(a_id) {
      projectTypeListByNoAuth({ pageNum: 1, pageSize: 100 }).then((res) => {
        this.projectType = res.data.data//.filter((v) => v.id == 17)
        if (a_id) this.form.setFieldsValue({ proTypeId: 17 })
      })
    },
    getLevelList() {
      let it = levelTypeList.find((v) => v.text == '项目与工作室')
      levelListByNoAuth({ pageNum: 1, pageSize: 100, type: it.id }).then((res) => {
        console.log(res)
        this.levelList = res.data.data
      })
      let its = levelTypeList.find((v) => v.text == '任务')
      levelListByNoAuth({ pageNum: 1, pageSize: 100, type: its.id }).then((res) => {
        console.log(res)
        this.levelTaskList = res.data.data
      })
    },

    handleOk() {
      let p = this.$refs.projectLevel
      let form = p.form
      form.validateFields((errors, values) => {
        if (!errors) {
          values.status = 1
          console.log(this.level.type)
          console.log(this.level.handleIndex)
          if (this.level.type == 'add') {
            this.level.list.push(values)
          } else if (this.level.handleIndex >= 0) {
            let handleIndex = this.level.handleIndex
            let list = cloneDeep(this.level.list)
            list[handleIndex] = { ...list[handleIndex], ...values }
            this.level.list = list
          }
          this.level.visible = false
          form.resetFields()
        }
      })
    },
    handleAdd() {
      this.level.visible = true
      this.level.type = 'add'
    },
    handleCancel() {
      this.level.visible = false
    },
    handleEdit(a_index) {
      this.level.visible = true
      this.level.type = 'edit'
      this.level.handleIndex = a_index
      this.level.mdl = cloneDeep(this.level.list[a_index])
    },
    handleDel(a_index) {
      console.log(a_index)
      this.level.list.splice(a_index,1)
      console.log(this.level.list)
      this.$forceUpdate()
    },

    // 积分

    handleAddIntegrel() {
      console.log(1111)
      this.integral.visible = true
      this.integral.mdl = cloneDeep(this.integral.data)
    },
    handleCancelIntegrel() {
      console.log(this.$refs.integralForm.form)
      this.integral.visible = false
      this.$refs.integralForm.form.resetFields()
    },
    handleEditIntegrel(a_index) {
      this.integral.visible = true
      this.integral.handleIndex = a_index
      this.integral.mdl = cloneDeep(this.level.list[a_index])
    },
    handleOkIntegrel() {
      let p = this.$refs.integralForm
      let form = p.form
      form.validateFields((errors, values) => {
        if (!errors) {
          this.integral.data = values
          form.resetFields()
        }
      })
      this.integral.visible = false
    },
  },
  filters: {
    projectFilter(val, a_list) {
      let it = a_list.find((v) => v.id == val)
      return it.name
    },
  },
  computed: {
    // c_list: function () {
    //   return this.level.list.filter((v) => v.status != -1)
    // },
    c_integral: function () {
      let data = this.integral.data
      let levelList = this.levelList
      let c_integral = []
      for (let i in data) {
        let it = levelList.find((v) => v.id == i)
        c_integral.push({
          name: it.name,
          num: data[i],
        })
      }
      return c_integral
    },
  },
}
</script>
